import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; public class OutOfOrderTest { // State private static /* volatile */ boolean flagDone; private static int result; // State for testing infrastructure private static final CyclicBarrier barrier = new CyclicBarrier(3); private static int i; public static void main(String[] args) throws InterruptedException, BrokenBarrierException { final Thread greenThread = new Thread(() -> { while (true) { try { barrier.await(); // Green thread from pseudocode result = 666; flagDone = true; barrier.await(); } catch (InterruptedException | BrokenBarrierException e) { throw new RuntimeException(e); } } }); final Thread blueThread = new Thread(() -> { while (true) { try { barrier.await(); // Blue thread from pseudocode if (flagDone) { // flagDone is true, so result should be ready! if (result == 0) System.out.println("Result is 0 at iteration " + i + "!"); } barrier.await(); } catch (InterruptedException | BrokenBarrierException e) { throw new RuntimeException(e); } } }); greenThread.start(); blueThread.start(); for (i = 0; /* loop forever */; ++i) { flagDone = false; result = 0; barrier.await(); // Let both threads run... barrier.await(); // ...and wait until they are done } } }